package com.gopay.bis.payease.ebank.operation;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.capinfo.crypt.Md5;
import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.bis.payease.ebank.crypt.GoPayRsaMd5;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.payease.ebank.PayEaseMessage;
import com.gopay.common.exception.GopayException;
import com.gopay.remote.bank.ICertHelper;

/**
 * 
 * @PayEaseCertHelper.java
 * @author Administrator
 * @2015-9-15 上午11:35:28 www.gopay.com.cn Inc.All rights reserved.
 */
public class PayEaseCertHelper implements ICertHelper {
	private final static Logger logger = LoggerFactory.getLogger(PayEaseCertHelper.class);
	
	private GoPayRsaMd5 goPayRsaMd5;
	
    public String sign(BaseMessage bsaeMessage) throws GopayException {
        try {
            PayEaseMessage message = (PayEaseMessage) bsaeMessage;
            BankLogUtils.printB2CSignPlainLog(message);
            Md5 md5 = new Md5("");
            md5.hmac_Md5(message.getPlainMessage(), message.getPrivateKeyPath());
            byte b[] = md5.getDigest();
            String digestString = md5.stringify(b);
            BankLogUtils.printB2CSignSignatureLog(message, digestString);
            return digestString;
        } catch (IOException e) {
            BankLogUtils.printB2CSignExceptionLog(bsaeMessage, e);
            throw new GopayException(ProcCodeConstants.PROC_CODE_100E6029);
        }
    }

    public Object verify(BaseMessage bsaeMessage) throws GopayException {
        try {
            PayEaseMessage message = (PayEaseMessage) bsaeMessage;
//            RSA_MD5 rsaMD5 = new RSA_MD5();
//            int k = rsaMD5.PublicVerifyMD5(message.getPublicKeyPath(), message.getVsign(), message.getPlainMessage());
            int k = goPayRsaMd5.publicVerifyMD5(message.getVsign(), message.getPlainMessage());
            if (k == 0) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
        	logger.error("PayEaseCertHelper verify fail :", e);
            BankLogUtils.printB2CVerifyExceptionLog(bsaeMessage, e);
            throw new GopayException(ProcCodeConstants.PROC_CODE_100E6031);
        }
    }

	public void setGoPayRsaMd5(GoPayRsaMd5 goPayRsaMd5) {
		this.goPayRsaMd5 = goPayRsaMd5;
	}
}
